package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.pojo.*;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RequestMapping("/clazzs")
@RestController
public class ClazzController {
    @Autowired
    private ClazzService clazzService;
    @Autowired
    private EmpService empService;

    @GetMapping
    public Result list(ClazzQueryParam Param) {
        log.info("查询班级列表");
        //1.创建条件分页  new 一个Page的对象<实体类>(页码,条数)
        Page<Clazz> clazzPage = new Page<>(Param.getPage(), Param.getPageSize());
          //给MyBatis Plus的分页查询添加排序条件
        clazzPage.addOrder(OrderItem.desc("update_time"));

        //做条件查询
        LambdaQueryWrapper<Clazz> cqw = new LambdaQueryWrapper<>();
        cqw.like(Param.getName()!=null&&Param.getName().length()>0,Clazz::getName,Param.getName());
        cqw.between(Param.getBegin()!=null&&Param.getEnd()!=null,Clazz::getBeginDate,Param.getBegin(),Param.getEnd());


        // 2. 执行分页查询
        Page<Clazz> page = clazzService.page(clazzPage,cqw);

        //班主任显示
        List<Clazz> records = page.getRecords();
        //使用Stream流中的的map吧getMasterId保留下来，然后筛选掉为null的 得到的结果储存到list集合中
        List<Integer> collect = records.stream().map(Clazz::getMasterId).filter(getMastrtId -> getMastrtId != null).collect(Collectors.toList());
        //判断collect是否有数据并且不为null
        if (collect != null && collect.size() > 0) {
            //listByIds() 是 MyBatis Plus提供的批量查询方法
//            List<Clazz> clazzes = clazzService.listByIds(collect);
            List<Emp> emps = empService.listByIds(collect);

            // 将部门的id和名称封装成一个map集合
            Map<Integer, String> map = emps.stream().collect(Collectors.toMap(emp -> emp.getId(), emp -> emp.getName()));

            //对班主任进行遍历
            for (Clazz clazz : records) {
                //然后把班主任的添加上去
                clazz.setMasterName(map.get(clazz.getMasterId()));
            }

        }

        // 3. 封装返回结果
        PageResult<Clazz> clazzPageResult = new PageResult<>(page.getTotal(), page.getRecords());
        return Result.success(clazzPageResult);
    }

    @PostMapping
    public Result save(@RequestBody Clazz clazz) {
        log.info("新增班级：{}", clazz);
        clazz.setUpdateTime(LocalDateTime.now());
        clazzService.save(clazz);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        log.info("根据id查询班级：{}", id);
        clazzService.getById(id);
        return Result.success();
    }

    @PutMapping
    public Result update(@RequestBody Clazz clazz) {
        log.info("修改班级：{}", clazz);
        clazz.setUpdateTime(LocalDateTime.now());
        clazzService.updateById(clazz);

        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        log.info("删除班级：{}", id);
        clazzService.removeById(id);
        return Result.success();
    }

    @GetMapping("/list")
    public Result list() {
        log.info("查询全部班级");
        clazzService.list();
        return Result.success();
    }
}
